package com.barry.utils;

import com.google.common.collect.Lists;
import lombok.extern.slf4j.Slf4j;

import java.io.*;
import java.util.List;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;

/**
 * @author Administrator
 * @version 1.0.0
 *  压缩包导出
 * create by 2018\8\10 0010 9:22
 */
@Slf4j
public class ZipUtil {
    private ZipUtil(){}
    /**
     * 功能:压缩文件
     */
    public static void zipFiles(List<File> srcFiles, File zipFile) throws Exception{
        try(OutputStream outputStream = new FileOutputStream(zipFile);
            ZipOutputStream out = new ZipOutputStream(outputStream)){
            for (int i = 0; i < srcFiles.size(); i++) {
                File file = srcFiles.get(i);
                String fileName = file.getName();
                byte[] buffer = new byte[1024];
                int len;
                //创建zip实体（一个文件对应一个ZipEntry）
                ZipEntry entry = new ZipEntry(fileName);
                try(FileInputStream is = new FileInputStream(srcFiles.get(i));
                    BufferedInputStream in = new BufferedInputStream(is)) {
                    //获取需要下载的文件流
                    out.putNextEntry(entry);
                    //文件流循环写入ZipOutputStream
                    while ((len = in.read(buffer)) != -1 ) {
                        out.write(buffer, 0, len);
                    }
                }
                file.deleteOnExit();
            }
        }
    }

    /**
     * 功能:压缩文件
     */
    @Deprecated
    public static void zipFiles2(List<File> srcFiles, File zipFile) throws Throwable{
        byte[] buf = new byte[1024];
        try(OutputStream outputStream = new FileOutputStream(zipFile);
            ZipOutputStream out = new ZipOutputStream(outputStream)){
            for (int i = 0; i < srcFiles.size(); i++) {
                try(FileInputStream in = new FileInputStream(srcFiles.get(i))) {
                    out.putNextEntry(new ZipEntry(srcFiles.get(i).getName()));
                    int len;
                    while ((len = in.read(buf)) > 0) {
                        out.write(buf, 0, len);
                    }
                    out.closeEntry();
                }
            }
        } catch (IOException e) {
            throw new Exception(e);
        }
    }

    public static void main(String[] args) throws Throwable {
        File f = new File("C:\\data\\bak\\excel");
        long start = System.currentTimeMillis();
        File out = new File("C:\\data\\bak\\out"+start+".zip");
        ZipUtil.zipFiles2(Lists.newArrayList(f.listFiles()), out);//未用缓冲流，大数据量文件会慢很多
        long end = System.currentTimeMillis();
        System.out.println((end-start)/1000);
        start = System.currentTimeMillis();
        out = new File("C:\\data\\bak\\out"+start+".zip");
        ZipUtil.zipFiles(Lists.newArrayList(f.listFiles()), out);
        end = System.currentTimeMillis();
        System.out.println((end-start)/1000);
    }
}
